package com.example.nutritionmate.controller;

import com.example.nutritionmate.dto.NutrientAmountDTO;
import com.example.nutritionmate.dto.NutritionFactDTO;
import com.example.nutritionmate.entity.User;
import com.example.nutritionmate.service.NutritionService;
import com.example.nutritionmate.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/nutrition") // 基于需求可以更改路径
public class NutritionController {

    @Autowired
    private NutritionService nutritionService;

    @Autowired
    private UserService userService;

    /**
     * 获取所有营养成分
     *
     * @return List<NutritionFactDTO>
     */
    @GetMapping("/all")
    public ResponseEntity<List<NutritionFactDTO>> getAllNutritionFacts() {
        List<NutritionFactDTO> nutritionFacts = nutritionService.getAllNutritionFacts();
        return ResponseEntity.ok(nutritionFacts);
    }

    /**
     * 获取当天所有营养摄入和
     *
     * @return List<NutritionAmountDTO>
     */
    @GetMapping("/getNutritionAmountByDate")
    public ResponseEntity<?> getNutritionByDate(@AuthenticationPrincipal UserDetails userDetails,
                                                                      @RequestParam String date) {
        // Spring Security 已经确保 userDetails 不为 null
        Optional<User> optionalUser = userService.findByUsername(userDetails.getUsername());

        User user = optionalUser.get();

        LocalDate localDate;
        try {
            localDate = LocalDate.parse(date);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("日期格式错误，正确格式为 YYYY-MM-DD");
        }

        List<NutrientAmountDTO> nutrientAmounts = nutritionService.getNutritionAmountByDate(user, localDate);
        return ResponseEntity.ok(nutrientAmounts);
    }
}
